var appPath = getAppPath();	
$(function(){
	
	$("#roleGrid").datagrid({
		url:appPath+'/system/role_pageList.do',
		height:'full',
		striped: true,
		remoteSort:false,
		queryParams: getQueryParam(),
		idField:'roleId',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true},
		      {field:'roleId',title:'操作',width:32,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    		  return "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showEdit("+rowIndex+")'/></a>";
		    	  }
		      }
		                ]],
		columns:[[
			  {field:'roleOrder',title:'角色序号',width:100,align:'left',sortable:true},
		      {field:'roleName',title:'角色名称',width:150,align:'left',sortable:true}
		      ]],
		 pagination:true,
		 rownumbers:true,
		 toolbar:[{
				id:'btnadd',
				text:'增加',
				iconCls:'icon-add',
				handler:function(){
					showAdd();
				}
			},'-',{
				id:'btndelMu',
				text:'删除',
				iconCls:'icon-cancel',
				handler:function(){
					var selections = $("#roleGrid").datagrid('getSelections');
					if(selections == null || selections == ''){
						$.messager.alert('提示信息','请选择要删除的数据','info');
						return ;
					}else{
						$.messager.confirm('提示信息','您确定要删除这些记录？',function(r){
							if(r){
								var ids = '';
								for(var i=0;i<selections.length;i++){
									ids += selections[i].roleId+',';
								}
								ids = ids.substring(0,ids.lastIndexOf(','));
								$.ajax({
									url:appPath+'/system/role_delMulti.do',
									data:{ids:ids},
									success:function(data){
										if(data!='ok'){
											$.messager.alert('提示信息','抱歉，删除未能完成，'+data,'error');
										}else{
											doReload('delete');
										}
									}
								});		
							}
						});
					}
				}
			}]
	});
});


/**
 * 展现增加页面
 */
function showAdd(){
	showPermission("add","");
	$('#addRoleForm').form('clear');
	$("#submitType").val("save");
	$('#addRoleDlg').window({
		        width: 800,  
                height:400,  
				title:'增加角色',
				iconCls:'icon-add',
				modal: true,
				shadow: true,
				collapsible:false,
				minimizable:false,
				maximizable:false
			});
	$('#addRoleDlg').window('move',{top:10,left:30});
	$('#addRoleDlg').window('open');
}


/**
 * 展现编辑页面
 * @param {} rowData
 */
function showEdit(rowIndex){
	var rowData = $("#roleGrid").datagrid("getRows")[rowIndex];
	showPermission("edit",rowData.roleId);
	$('#addRoleForm').form('clear');
	$('#addRoleForm').form('load',rowData);
	$("#submitType").val("update");
	$('#addRoleDlg').window({
			width: 800,  
	        height:400, 
			title:'编辑角色',
			iconCls:'icon-edit',
			modal: true,
			shadow: true,
			collapsible:false,
			minimizable:false,
			maximizable:false
		});
	$('#addRoleDlg').window('move',{top:10,left:30});
	$('#addRoleDlg').window('open');
}

/**
 * 根据roleId获取权限信息
 */
function getPermissionByRoleId(roleId,moduleIdList){
	$.ajax({
		url:appPath+'/system/role_listPermissionsByRoleId.do?roleId='+roleId,
		type:"post",
		dataType: 'json',   //返回值类型 
		success:function(json){
			for(var i = 0;i<json.length;i++){
				$("#permissionId"+json[i]).prop("checked",true);
			}
			for(var j =0;j<moduleIdList.length;j++){
				changeStatu(moduleIdList[j].moduleId);
			}
		}
	});
}



/**
 * 获取所有权限信息
 */
function showPermission(type,roleId){
	$("#permissionDate").nextAll().remove();
	$.ajax({
		url:appPath+'/system/role_listAllPermissions.do',
		type:"post",
		dataType: 'json',   //返回值类型 
		success:function(json){
			var str="";
			for(var i = 0;i < json.moduleIdList.length ; i++){
				str = str + "<tr height='25px'><td   style='border:0';style='font-size : 16px' colspan='5'><input  id='moduleId"+json.moduleIdList[i].moduleId+"'  type='checkbox'  onclick='selectAllPermission(\""+json.moduleIdList[i].moduleId+"\");'>"+json.moduleIdList[i].moduleName+"</input></td></tr>";
				str = str + "<tr height='25px' >";
				for(var j = 0;j <json.moduleIdList[i].permissionList.length;j++){
					if(j == 0){
         				str = str + "<td width ='4%' style='border:0;font-size : 16px;'>&nbsp;&nbsp;</td>";
         				str = str +"<td  width='24%'  style='border:0;font-size : 16px;'><input id='permissionId"+json.moduleIdList[i].permissionList[j].permissionId+"'  class='selected"+json.moduleIdList[i].moduleId+"' type='checkbox' value='"+json.moduleIdList[i].permissionList[j].permissionId+"' onclick='changeStatu(rowData\""+json.moduleIdList[i].moduleId+"\");'>"+json.moduleIdList[i].permissionList[j].permissionName+"</input></td>";
         			}
					else if(j%4==0 && j!=0){
         				str = str +"</tr><tr height='25px' ><td width ='4%' style='border:0;font-size : 16px;'>&nbsp;&nbsp;</td>";
         				str = str +"<td  width='24%'  style='border:0;font-size : 16px;'><input  id='permissionId"+json.moduleIdList[i].permissionList[j].permissionId+"'  class='selected"+json.moduleIdList[i].moduleId+"' type='checkbox' value='"+json.moduleIdList[i].permissionList[j].permissionId+"' onclick='changeStatu(\""+json.moduleIdList[i].moduleId+"\");'>"+json.moduleIdList[i].permissionList[j].permissionName+"</input></td>";
         			}
         			else{
         				str = str +"<td  width='24%'  style='border:0;font-size : 16px;'><input id='permissionId"+json.moduleIdList[i].permissionList[j].permissionId+"'  class='selected"+json.moduleIdList[i].moduleId+"' type='checkbox' value='"+json.moduleIdList[i].permissionList[j].permissionId+"' onclick='changeStatu(\""+json.moduleIdList[i].moduleId+"\");'>"+json.moduleIdList[i].permissionList[j].permissionName+"</input></td>";
         			}
         		}
				str = str +"</tr>";
			}
			$("#permissionDate").after(str);
			if(type == "edit"){
				getPermissionByRoleId(roleId,json.moduleIdList);
			}
			
		}
	});
}


/**
 * 点击模块的checkbox，选择该模块下所有子模块
 */
function selectAllPermission(moduleId){
	var select= $("#moduleId"+moduleId+":checked").length;
	if(select == 1){
		$(".selected"+moduleId).prop("checked",true);
	}
	if(select == 0){
		$(".selected"+moduleId).prop("checked",false);
	}
}

/**
 * 点击权限的checkbox，若该类全选中，则模块被选中，若该类没有全选中，则模块选中被取消
 */
function changeStatu(moduleId){
	var select= $(".selected"+moduleId+":not(:checked)").length;
	if(select == 0){
		$("#moduleId"+moduleId).prop("checked",true);
	}
	if(select != 0){
		$("#moduleId"+moduleId).prop("checked",false);
	}
}

/**
 * 提交数据（包括增加，修改）
 */
function doPostData(){
	if(!$('#addRoleForm').form('validate')){
		return ;
	}
	var type = $("#submitType").val();
	var typeStr = "";
	if(type == "save"){
		typeStr = "保存";
	}else if(type == "update"){
		typeStr = "更新";
	}
	var subData = $('#addRoleForm');  
	var pers = new Array()
	var k = 0;
	$("#addRoleDlg input:checked").each(function(i){
		var value = $(this).val();
		if(value != "on"){
			pers[k] = value;
			k++;
		}
	})
	var roleinfo = subData.serialize(); 
	$.ajax({
		url:appPath+'/system/role_'+type + '.do?permissionIds='+pers,
		type:"post",
		data:roleinfo,
		success:function(data){
			if(data!='ok'){
				if(data == 'repeat'){
					$.messager.alert('提示信息','该角色序号或角色名称已存在！','info');
				}else{
					$.messager.alert('提示信息','抱歉，'+typeStr+'未能完成，'+data,'error');	
				}
			}else{
				doReload(type);
				$('#addRoleDlg').window('close');
			}
		}
	});
}

function cancelPostData(){
	$('#addRoleDlg').window('close');
}





/**
 * 获取请求信息
 * @return {}
 */
function getQueryParam(){
	var submitObject = new Object();
	submitObject.name = $('#queryRoleName').val();
	return submitObject;
}

/**
 * 查询数据
 */
function doQuery(){
	$("#roleGrid").datagrid('unselectAll');
	$("#roleGrid").datagrid('load',getQueryParam());
}

/**
 * 重载grid，取消全选
 */
function doReload(type){
	var ops = $('#roleGrid').datagrid('getPager').pagination("options");
	if(type == "save"){
		var pn = Math.floor(ops.total/ops.pageSize)+1;
		$('#roleGrid').datagrid('getPager').pagination({pageNumber:pn});
		$('#roleGrid').datagrid('options').pageNumber = pn;
	}else if(type == "delete"){
		if($('#roleGrid').datagrid('getRows').length == $('#roleGrid').datagrid('getSelections').length){
			var pn ;
			var pnt = Math.ceil(ops.total/ops.pageSize);
			var pm = ops.pageNumber;
			if(pnt == (pm-1)){
				pn = pnt ;
			}else{
				pn = pm
			}
			$('#roleGrid').datagrid('getPager').pagination({pageNumber:(pn==0?1:pn)});
			$('#roleGrid').datagrid('options').pageNumber = (pn==0?1:pn);
		}
	}
	$("#roleGrid").datagrid('unselectAll');
	$("#roleGrid").datagrid('reload');
}